package binary_tree

import "container/list"

func TreeMaxWidth(head *TreeNode) int {
	res := 0
	if head == nil {
		return res
	}
	queue := list.New()
	var nextEnd *TreeNode
	curEnd := head
	queue.PushFront(head)
	curLevelSize := 0
	for queue.Len() > 0 {
		node := queue.Remove(queue.Back()).(*TreeNode)
		curLevelSize++
		if node.Left != nil {
			nextEnd = node.Left
			queue.PushFront(node.Left)
		}
		if node.Right != nil {
			nextEnd = node.Right
			queue.PushFront(node.Right)
		}
		if node == curEnd {
			res = max(curLevelSize, res)
			curLevelSize = 0
			curEnd = nextEnd
		}
	}
	return res
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}